package com.bc.ui;

import java.util.HashMap;

import net.youmi.android.AdManager;
import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;

import cn.waps.AppConnect;

import com.bc.R;
import com.bc.db.entity.BtcNews;
import com.bc.service.deal.BtcCategory;
import com.bc.ui.ad.QuitPopAd;
import com.bc.ui.setting.SettingActivity;
import com.bc.utils.CommonUtils;
import com.bc.utils.Constants;
import com.bc.utils.SettingPrefs;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.MenuCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends BaseActivity {
	private static final String TAG = "MainActivity";
	PullToRefreshListView mRefreshListView;
    private BTCNewsAdapter mAdapter;
    
    private BtcCacheOperator mBtcCacheOperator;
    private Handler mHandler = new Handler();
    
    
    public Drawable down, up;
    
    private LocalBroadcastManager mBroadcastManager;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initView();
		
		ActionBar actionBar = getSupportActionBar();  
        actionBar.setDisplayShowHomeEnabled(true);  
		mBtcCacheOperator = BtcCacheOperator.getInstance();
		
		initDrawable();
		
		Constants.RELEASE_YOUMI = false;
		Constants.RELEASE_WAPS = true;
		//waps
		AppConnect.getInstance("d4f4f31e68adfab641a14c68ae9376b7","default",this);
		
		AppConnect.getInstance(this).initPopAd(this);
		
		AppConnect.getInstance(this).initAdInfo();
		
		LinearLayout adlayout = (LinearLayout)findViewById(R.id.AdLinearLayout); 
		AppConnect.getInstance(this).showBannerAd(this, adlayout);
		
		//youmi
		 AdManager.getInstance(this).init("61438c43238d97d7", "0cc16914db6e9ca6", false);
		 AdView adView = new AdView(this, AdSize.FIT_SCREEN);
		    //获取要嵌入广告条的布局
		 LinearLayout adLayout = (LinearLayout)findViewById(R.id.adLayout);
		    //将广告条加入到布局中
		 adLayout.addView(adView);
		 
		 mBroadcastManager = LocalBroadcastManager.getInstance(MainActivity.this);
		 IntentFilter filter = new IntentFilter();
		 filter.addAction(Constants.ACTION_SHOW_LOADING_REFRESH);
		 filter.addAction(Constants.ACTION_HIDE_LOADING_REFRESH);
		 mBroadcastManager.registerReceiver(btcBroadcastReceiver, filter);
		 mHandler.postDelayed(runnable, 1500);
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	public void onRefreshData() {
		MenuItemCompat.getActionView(refreshMenuItem).setVisibility(View.VISIBLE);
		Intent intent = new Intent(BtcService.ACTION_NETWORK_BTCNEWS);
		mBroadcastManager.sendBroadcast(intent);
	}
	
	
	Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			refreshBtcNews();
		}
	};
	
	public void refreshBtcNews() {
		if (mRefreshListView.isRefreshing()) {
			mRefreshListView.onRefreshComplete();
		}
		if (refreshMenuItem != null) {
			MenuItemCompat.getActionView(refreshMenuItem).setVisibility(View.GONE);
		}
		mAdapter.notifyDataSetChanged();
	}

	public void bindViewData(BtcCategory btcCg, View convertView, int position) {
		ImageView imageView = (ImageView)convertView.findViewById(R.id.image);
		TextView tvLastSale = (TextView)convertView.findViewById(R.id.last_sale);
		TextView tvBuy = (TextView)convertView.findViewById(R.id.buy);
		TextView tvSell = (TextView)convertView.findViewById(R.id.sell);
		if (mBtcCacheOperator.getEnabledBtcNews().size() <= position) {
			return;
		}
		BtcNews btcNews = mBtcCacheOperator.getEnabledBtcNews().get(position);
		if (btcNews != null) {
			ImageLoader.getInstance().displayImage("assets://" + btcNews.btcIcon.trim() + ".png", imageView, options);
		}
		
		if (btcCg != null) {
			
			HashMap<String, Object> hashMap = btcCg.getBtcNews();
			convertView.setTag(hashMap);
			
			BtcCategory bCategory = mBtcCacheOperator.getBtcCategoryFromMap(btcNews.btcType);
			HashMap<String, Object> lastDataHashMap = bCategory != null ? bCategory.getBtcNews() : null;
			
			Object lastObject = hashMap.get(Constants.LAST_SALE_PRICE);
			String lastSale = CommonUtils.ToString(lastObject);
			if (!TextUtils.isEmpty(lastSale)) {
				tvLastSale.setText(CommonUtils.DisplayFormatString(btcNews.btcType, lastSale, MainActivity.this));
			} 
			if (lastDataHashMap != null) {
				Object oldObj = lastDataHashMap.get(Constants.LAST_SALE_PRICE);
				setDrawable(lastObject, oldObj, tvLastSale);
			}
			
			
			
			Object buyObject = hashMap.get(Constants.BUY_ONE_PRICE);
			String buyPrice = CommonUtils.ToString(buyObject);
			if (!TextUtils.isEmpty(buyPrice)) {
				tvBuy.setText(CommonUtils.DisplayFormatString(btcNews.btcType, lastSale, MainActivity.this));
			} 
			if (lastDataHashMap != null) {
				setDrawable(buyObject, lastDataHashMap.get(Constants.BUY_ONE_PRICE), tvBuy);
			}
			
			
			
			Object sellObject = hashMap.get(Constants.SELL_ONE_PRICE);
			String sellPrice = CommonUtils.ToString(sellObject);
			if (!TextUtils.isEmpty(sellPrice)) {
				tvSell.setText(CommonUtils.DisplayFormatString(btcNews.btcType, sellPrice, MainActivity.this));
			} 
			if (lastDataHashMap != null) {
				setDrawable(sellObject, lastDataHashMap.get(Constants.SELL_ONE_PRICE), tvSell);
			}
		}
	}
	
	public void initDrawable() {
		down = getResources().getDrawable(R.drawable.down);
		up = getResources().getDrawable(R.drawable.up);
		down.setBounds(0, 0, down.getMinimumWidth(), down.getMinimumHeight()); 
		up.setBounds(0, 0, up.getMinimumWidth(), up.getMinimumHeight()); 
	}
	
	public void initView() {
		mRefreshListView = (PullToRefreshListView)findViewById(R.id.xlist);
		ListView mListView = mRefreshListView.getRefreshableView();
		mRefreshListView.setMode(Mode.PULL_FROM_START);
		mRefreshListView.setOnRefreshListener(mOnRefreshListener);
		mAdapter = new BTCNewsAdapter();
		mListView.setAdapter(mAdapter);
		View view = LayoutInflater.from(this).inflate(R.layout.adapter_main_head_layout, mListView, false);
		mListView.addHeaderView(view);
		view.setClickable(false);
		mListView.setOnItemClickListener(itemClickListener);
	}
	
	OnRefreshListener<ListView> mOnRefreshListener = new OnRefreshListener<ListView>() {

		@Override
		public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			onRefreshData();
		}
	};
	
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			if (position ==0 || position == 1) {
				return;
			}
			BtcNews bc = mBtcCacheOperator.getEnabledBtcNews().get(position - 2);
			HashMap<String, Object> hashMap = (HashMap<String, Object>) view.getTag();
			if (hashMap != null && hashMap.size() > 0) {
				Intent intent = new Intent(MainActivity.this, DetailActivity.class);
				intent.putExtra(Constants.LAST_SALE_PRICE, CommonUtils.ToString(hashMap.get(Constants.LAST_SALE_PRICE)));
				intent.putExtra(Constants.BUY_ONE_PRICE, CommonUtils.ToString(hashMap.get(Constants.BUY_ONE_PRICE)));
				intent.putExtra(Constants.SELL_ONE_PRICE, CommonUtils.ToString(hashMap.get(Constants.SELL_ONE_PRICE)));
				intent.putExtra(Constants.SELL_HIGH_PRICE, CommonUtils.ToString(hashMap.get(Constants.SELL_HIGH_PRICE)));
				intent.putExtra(Constants.SELL_LOW_PRICE, CommonUtils.ToString(hashMap.get(Constants.SELL_LOW_PRICE)));
				intent.putExtra(Constants.SALE_VOLUME, CommonUtils.ToString(hashMap.get(Constants.SALE_VOLUME)));
				intent.putExtra(Constants.BTC_NAME_COL, bc.btcName);
				intent.putExtra(Constants.BTC_TYPE_COL, bc.btcType);
				startActivity(intent);
				overridePendingTransition(R.anim.push_in_bottom, R.anim.base_stay_orig);
			}
		}
	};
	
	public BroadcastReceiver btcBroadcastReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.d(TAG, "receive a broadcast Action is " + intent.getAction());
			if (intent.getAction().equals(Constants.ACTION_SHOW_LOADING_REFRESH)) {
				
				if (refreshMenuItem != null) {
					MenuItemCompat.getActionView(refreshMenuItem).setVisibility(View.VISIBLE);
				}
			} else if (intent.getAction().equals(Constants.ACTION_HIDE_LOADING_REFRESH)) {
				refreshBtcNews();
			}
		}
	};
	public static DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
			.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY).build();
	
	class BTCNewsAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			return BtcCacheOperator.getInstance().getBtcCategories().size();
		}

		@Override
		public Object getItem(int position) {
			return BtcCacheOperator.getInstance().getBtcCategories().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public void notifyDataSetChanged() {
//			synchronized (this) {
				super.notifyDataSetChanged();
//			}
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.adapter_main_layout, parent, false);
			}
			
			BtcCategory btcCg = (BtcCategory) getItem(position);
			bindViewData(btcCg, convertView, position);
			return convertView;
		}
	}
	
	
	public void setDrawable(Object newObj, Object oldObj, TextView textView) {
		if (CommonUtils.BigThan(newObj, oldObj) < 0) {
			textView.setCompoundDrawables(null, null, down, null);
			textView.setTextColor(getResources().getColor(R.color.noti_red));
		} else if (CommonUtils.BigThan(newObj, oldObj) > 0) {
			textView.setCompoundDrawables(null, null, up, null);
			textView.setTextColor(getResources().getColor(R.color.noti_green));
		} else {
			textView.setCompoundDrawables(null, null, null, null);
			textView.setTextColor(getResources().getColor(R.color.black));
		}
	}
	
	private MenuItem refreshMenuItem;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		refreshMenuItem = menu.findItem(R.id.action_refresh);
		MenuItemCompat.setActionView(refreshMenuItem, R.layout.action_progressbar);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent intent = new Intent(MainActivity.this, SettingActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_in_right, R.anim.push_out_left);
			break;
		default:
			break;
		}
		return true;
	}
	
	@Override
	protected void onDestroy() {
		mBroadcastManager.unregisterReceiver(btcBroadcastReceiver);
		super.onDestroy();
	}
	
	private static final int dexTime = 3000;
	private long lastTime;
	@Override
	public void onBackPressed() {
		if (Constants.RELEASE_WAPS) {
			QuitPopAd.getInstance().show(this);
		} else {
			long now = System.currentTimeMillis();
			if (now - lastTime > dexTime) {
				lastTime = now;
				
				Toast.makeText(MainActivity.this, getString(R.string.back_exit_tip), Toast.LENGTH_SHORT).show();
			} else {
				super.onBackPressed();
			}
		}
	}
}
